import {useUserStore} from '@/stores/user'
import to from 'await-to-js'
import {fetchAliyunOSSUploadPayload} from '@/api/aliyun'
import {tip} from '@/utils/uni-api-wrap/toast'
import {getFileNameAndExtension} from '@/utils/utils'

export const previewImage = (urls = [], opts = {}) => uni.previewImage({ urls, ...opts })

export const uploadFile = async (filePath = []) => {
  const [uploadPayloadErr, uploadPayloadResult] = await to(fetchAliyunOSSUploadPayload({ data: getFileNameAndExtension(filePath).extension }))
  if (uploadPayloadErr) return
  if (uploadPayloadResult.code !== 0) return tip(uploadPayloadResult.msg || '获取阿里云OSS上传凭证失败')
  const aliyunOSSUploadPayload = uploadPayloadResult?.data
  const userStore = useUserStore()
  const formData = {
    name: filePath,
    success_action_status: "200",
    key: aliyunOSSUploadPayload?.key,//上传图片的名字和路径（默认路径根目录，自定义目录：xxx/xxx.png）
    policy: aliyunOSSUploadPayload?.policy,
    OSSAccessKeyId: aliyunOSSUploadPayload?.accessId,
    expire: aliyunOSSUploadPayload?.expire,
    signature: aliyunOSSUploadPayload?.signature,
  }
  console.log('uploadFile Before FormData', formData)
  const [err, result] = await to(uni.uploadFile({
    url: aliyunOSSUploadPayload?.host,
    filePath,
    fileType: 'image',
    formData,
    name: 'file'
  }))
  if (err) return Promise.reject(new Error(result.errMsg))
  if (result.statusCode !== 200) return Promise.reject(new Error(result.errMsg))
  return Promise.resolve(aliyunOSSUploadPayload?.url)
}

export const chooseImage = (opt = {}) => new Promise((resolve, reject) => {
  uni.chooseMedia({
    mediaType: ['image'],
    success({ tempFiles, errMsg }) {
      if (errMsg !== 'chooseMedia:ok') {
        resolve(errMsg)
      } else {
        resolve(tempFiles)
      }
    },
    fail: reject,
    ...opt
  })
})

export const createVideoContext = (videoId, currentComponent) => uni.createVideoContext(videoId, currentComponent)
